﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using MySql.Data.MySqlClient;
using Services.Common;
using BartonExtension;
using SQLWrapper;
using Model.App;
using Model.Images;
using Model.Weixin;
using Model;

namespace Services.Group
{
    public class ISMGroupServiceProvider : ISMServiceProvider
    {
        public const string GET_GROUP_LIST = "get_group_list";
        public const string GET_GROUP_INFO = "get_group_info";
        public const string CREATE_GROUP = "create_group";
        public const string JOIN_GROUP = "join_group";
        public const string PROCESS_JOIN_REQUEST = "process_join_request";
        public const string CHECK_IS_USER_JOINED_GROUP = "check_is_user_joined_group";
        public const string SEND_MESSAGE_TO_GROUP = "send_message_to_group";
        public const string DISMISS_GROUP = "dismiss_group";
        public const string EXIT_GROUP = "exit_group";
        public const string GET_GROUP_MEMBERS = "get_group_members";
        public const string GET_GROUP_MESSAGES = "get_group_messages";
        public const string GET_GROUP_JOINS = "get_group_joins";
        public const string GET_GROUP_MESSAGE_COMMENTS = "get_group_message_comments";
        public const string ADD_GROUP_MESSAGE_COMMENT = "add_group_message_comment";
        public const string GET_SINGLE_GROUP_MESSAGE = "get_single_group_message";

        public override Task<ISMServiceResult> doProcess(ISMServiceModel model)
        {
            if(model.operationIdentifier == GET_GROUP_LIST)
            {
                ISMGetGroupRequest request = model.GetState<ISMGetGroupRequest>();
                return GetGroupList(request);
            }
            else if(model.operationIdentifier == GET_GROUP_INFO)
            {
                ISMGetGroupInfoRequest request = model.GetState<ISMGetGroupInfoRequest>();
                return GetGroupInfo(request);
            }
            else if(model.operationIdentifier == CREATE_GROUP)
            {
                ISMCreateGroupRequest request = model.GetState<ISMCreateGroupRequest>();
                return CreateGroup(request);
            }
            else if(model.operationIdentifier == JOIN_GROUP)
            {
                ISMJoinGroupRequest request = model.GetState<ISMJoinGroupRequest>();
                return JoinGroup(request);
            }
            else if(model.operationIdentifier == PROCESS_JOIN_REQUEST)
            {
                ISMExecuteJoinRequest request = model.GetState<ISMExecuteJoinRequest>();
                return ExecuteJoinRequest(request);
            }
            else if(model.operationIdentifier == SEND_MESSAGE_TO_GROUP)
            {
                ISMCreateGroupMessageRequest request = model.GetState<ISMCreateGroupMessageRequest>();
                return SendMessageToGroup(request);
            }
            else if(model.operationIdentifier == CHECK_IS_USER_JOINED_GROUP)
            {
                ISMCheckUserInGroupRequest request = model.GetState<ISMCheckUserInGroupRequest>();
                return CheckIfUserJoined(request);
            }
            else if(model.operationIdentifier == GET_GROUP_MEMBERS)
            {
                ISMGetGroupMembersRequest request = model.GetState<ISMGetGroupMembersRequest>();
                return GetGroupMembers(request);
            }
            else if(model.operationIdentifier == GET_GROUP_MESSAGES)
            {
                ISMGetGroupMessageRequest request = model.GetState<ISMGetGroupMessageRequest>();
                return GetGroupMessages(request);
            }
            else if(model.operationIdentifier == DISMISS_GROUP)
            {
                ISMDismissGroupRequest request = model.GetState<ISMDismissGroupRequest>();
                return DismissGroup(request);
            }
            else if(model.operationIdentifier == EXIT_GROUP)
            {
                ISMRemoveUserFromGroupRequest request = model.GetState<ISMRemoveUserFromGroupRequest>();
                return RemoveMemberFromGroup(request);
            }
            else if(model.operationIdentifier == GET_GROUP_JOINS)
            {
                ISMGetGroupJoinRequest request = model.GetState<ISMGetGroupJoinRequest>();
                return GetGroupJoins(request);
            }
            else if(model.operationIdentifier == GET_SINGLE_GROUP_MESSAGE)
            {
                ISMGetSingleGroupMessageRequest request = model.GetState<ISMGetSingleGroupMessageRequest>();
                return GetSingleGroupMessage(request);
            }
            else if(model.operationIdentifier == GET_GROUP_MESSAGE_COMMENTS)
            {
                ISMGetGroupMessageCommentsRequest request = model.GetState<ISMGetGroupMessageCommentsRequest>();
                return GetGroupMessageComments(request);
            }
            else if (model.operationIdentifier == ADD_GROUP_MESSAGE_COMMENT)
            {
                ISMAddGroupMessageCommentRequest request = model.GetState<ISMAddGroupMessageCommentRequest>();
                return AddGroupMessageComment(request);
            }
            else
            {
                return base.defaultProcess();
            }
        }
        private Task<ISMServiceResult> GetGroupList(ISMGetGroupRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                        {
                            cmd.CommandText = "proc_client_get_groups";
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?startIdx", request.page * request.pageSize, ParameterDirection.Input);
                            cmd.Parameters.Add("?endIdx", (request.page + 1) * request.pageSize, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.dbReturningState = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        },
                        data =>
                        {
                            if(data.Count == 1 && data.First().ContainsKey("error"))
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证失败";
                            }
                            else
                            {
                                List<ISMGroup> groups = new List<ISMGroup>();
                                data.ForEach(d =>
                                    {
                                        ISMGroup group = new ISMGroup()
                                        {
                                            ID = d["ID"].toUInt64().Value,
                                            group_name = d["group_name"].ToString(),
                                            group_desc = d["group_desc"].ToString(),
                                            creator = new ISMUserinfo()
                                            {
                                                ID = d["uid"].ToString().toInt64().Value,
                                                openId = d["openid"].ToString(),
                                                intopenid = d["intopenid"].ToString(),
                                                wechatName = d["wechatname"].ToString(),
                                                username = d["username"].ToString(),
                                                sex = (Sex)d["sex"].ToString().toInt32().Value,
                                                vocation = d["vocation"].ToString(),
                                                company = d["company"].ToString(),
                                                occupation = d["occupation"].ToString(),
                                                mobile = d["mobile"].ToString(),
                                                telephone = d["telephone"].ToString(),
                                                email = d["email"].ToString(),
                                                officeAddress = d["officeaddress"].ToString(),
                                                piccardUrl = d["piccardUrl"].ToString(),
                                                videocardUrl = d["piccardUrl"].ToString(),
                                                headimgUrl = d["headimgUrl"].ToString()
                                            },
                                            role = new ISMGroupPolicyRole()
                                            {
                                                group_policy_role_display_name = d["group_policy_role_display_name"].ToString(),
                                                group_policy_role_name = d["group_policy_role_name"].ToString(),
                                                enable_rules = new List<ISMGroupPolicyRule>()
                                            }
                                        };
                                        //Parse policies
                                        List<ISMGroupPolicyRule> rules = new List<ISMGroupPolicyRule>();
                                        var policy_rules = d["policy_rules"].ToString();
                                        policy_rules.Split('&').ToList().ForEach(rule =>
                                        {
                                            ISMGroupPolicyRule _rule = new ISMGroupPolicyRule()
                                            {
                                                group_policy_rule_value = rule.Split(';')[0].toEnum<GroupRule>(),
                                                group_policy_rule_display_name = rule.Split(';')[1].ToString(),
                                                group_policy_rule_name = rule.Split(';')[2].ToString()
                                            };
                                            rules.Add(_rule);
                                        });
                                        group.role.enable_rules = rules;

                                        //Parse Image
                                        string img = d["img_url"].ToString();
                                        if (img != "#na")
                                        {
                                            Model.Images.UploadImageEntity entity = new Model.Images.UploadImageEntity()
                                            {
                                                imageID = d["img_id"].toInt64().Value,
                                                ori_image_url = img
                                            };
                                            entity.generateThumbs();
                                            group.group_image = entity;
                                        }
                                        groups.Add(group);
                                    });
                                result.dbReturningState = groups;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> CreateGroup(ISMCreateGroupRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperation(cmd =>
                        {
                            cmd.CommandText = "proc_client_create_group";
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_group_name", request.group_name, ParameterDirection.Input);
                            cmd.Parameters.Add("?_group_desc", request.group_desc, ParameterDirection.Input);
                            cmd.Parameters.Add("?_group_image_id", request.group_image_id == null ? "" : request.group_image_id, ParameterDirection.Input);
                            cmd.Parameters.Add("?_tags", request.parameterState == null ? "" : request.parameterState, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                            cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                            cmd.ExecuteNonQuery();
                            int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                            if(errorcode == -1)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证失败";
                            }
                            else if(errorcode == -2)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_IS_ALREADY_EXISTS;
                                result.errorMsg = "该群组已存在";
                            }
                            else if (errorcode == -3)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                                result.errorMsg = "标签添加失败";
                            }
                            else if (errorcode == -4)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                                result.errorMsg = "未知错误";
                            }
                        }, 
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        },CommandType.StoredProcedure,false);
                    return result;
                });
        }
        private Task<ISMServiceResult> GetGroupInfo(ISMGetGroupInfoRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                {
                    cmd.CommandText = "proc_client_get_groupinfo";
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                }, 
                e =>
                {
                    if(e != null)
                    {
                        result.isOperationSuccess = false;
                        result.errorMsg = e;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                    }
                },
                data =>
                {
                    if(data.Count == 1 && data.First().ContainsKey("error"))
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    else
                    {
                        if (data.Count == 0)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                            result.errorMsg = "未找到群组";
                        }
                        else
                        {
                            var d = data.First();
                            ISMGroup group = new ISMGroup()
                            {
                                ID = d["ID"].toUInt64().Value,
                                group_name = d["group_name"].ToString(),
                                group_desc = d["group_desc"].ToString(),
                                memberCount = d["memberCount"].toUInt64().Value,
                                lastestGroupMessage = d["lastestGroupMessage"].ToString(),
                                timetag = d["timetag"].ToString(),
                                creator = new ISMUserinfo()
                                {
                                    ID = d["uid"].ToString().toInt64().Value,
                                    openId = d["openid"].ToString(),
                                    intopenid = d["intopenid"].ToString(),
                                    wechatName = d["wechatname"].ToString(),
                                    username = d["username"].ToString(),
                                    sex = (Sex)d["sex"].ToString().toInt32().Value,
                                    vocation = d["vocation"].ToString(),
                                    company = d["company"].ToString(),
                                    occupation = d["occupation"].ToString(),
                                    mobile = d["mobile"].ToString(),
                                    telephone = d["telephone"].ToString(),
                                    email = d["email"].ToString(),
                                    officeAddress = d["officeaddress"].ToString(),
                                    piccardUrl = d["piccardUrl"].ToString(),
                                    videocardUrl = d["piccardUrl"].ToString(),
                                    headimgUrl = d["headimgUrl"].ToString()
                                }
                            };
                            if(d.ContainsKey("group_policy_role_display_name"))
                            {
                                group.role = new ISMGroupPolicyRole()
                                {
                                    group_policy_role_display_name = d["group_policy_role_display_name"].ToString(),
                                    group_policy_role_name = d["group_policy_role_name"].ToString(),
                                    enable_rules = new List<ISMGroupPolicyRule>()
                                };

                                //Parse policies
                                List<ISMGroupPolicyRule> rules = new List<ISMGroupPolicyRule>();
                                var policy_rules = d["policy_rules"].ToString();
                                policy_rules.Split('&').ToList().ForEach(rule =>
                                {
                                    ISMGroupPolicyRule _rule = new ISMGroupPolicyRule()
                                    {
                                        group_policy_rule_value = rule.Split(';')[0].toEnum<GroupRule>(),
                                        group_policy_rule_name = rule.Split(';')[1].ToString(),
                                        group_policy_rule_display_name = rule.Split(';')[2].ToString()
                                    };
                                    rules.Add(_rule);
                                });
                                group.role.enable_rules = rules;
                            }
                            result.dbReturningState = group;
                        }
                    }
                }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> JoinGroup(ISMJoinGroupRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                {
                    cmd.CommandText = "proc_client_request_join_request";
                    cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?_content", request.content, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                    cmd.ExecuteNonQuery();
                    int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                    if(errorcode == -1)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    else if(errorcode == -2)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                        result.errorMsg = "该群已解散";
                    }
                },
                e =>
                {
                    if(e != null)
                    {
                        result.isOperationSuccess = false;
                        result.errorMsg = e;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                    }
                }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> ExecuteJoinRequest(ISMExecuteJoinRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                {
                    cmd.CommandText = "proc_client_process_group_join_request";
                    cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?_status", request.status, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                    cmd.ExecuteNonQuery();
                    int errrorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                    if(errrorcode == -1)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    else if(errrorcode == -2)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                        result.errorMsg = "该群组不存在";
                    }
                    else if(errrorcode == -3)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_JOIN_REQUEST_IS_ALREADY_PROCESSED;
                        result.errorMsg = "该加群请求已处理过";
                    }
                    else if(errrorcode == -4)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_USER_IS_ALREADY_JOINED;
                        result.errorMsg = "该用户已加入群组";
                    }
                    else if (errrorcode == -5)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                        result.errorMsg = "该群已解散";
                    }
                },
                e =>
                {
                    if(e != null)
                    {
                        result.isOperationSuccess = false;
                        result.errorMsg = e;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                    }
                }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> SendMessageToGroup(ISMCreateGroupMessageRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                    {
                        cmd.CommandText = "proc_client_send_message_to_group";
                        cmd.Parameters.Add("?_groupids", request.group_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?_share_id", request.share_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?_content",request.content == null ? "" : request.content,ParameterDirection.Input);
                        cmd.Parameters.Add("?_uid",request.uid,ParameterDirection.Input);
                        cmd.Parameters.Add("?_message_type",request.type,ParameterDirection.Input);
                        cmd.Parameters.Add("?_image_ids", request.image_ids == null ? "" : request.image_ids, ParameterDirection.Input);
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                        cmd.ExecuteNonQuery();
                        int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                        if(errorcode == -1)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            result.errorMsg = "Token 验证失败";
                        }
                        else if(errorcode == -2)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = "你不属于该组";
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_AUTHORIZERIGHTSFAIL;
                        }
                        else if(errorcode == -3)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = "该群已解散";
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                        }
                    },
                    e =>
                    {
                        if(e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = e;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                        }
                    }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> CheckIfUserJoined(ISMCheckUserInGroupRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                    {
                        cmd.CommandText = "proc_client_check_is_user_joined_group";
                        cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                        cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                        cmd.Parameters.Add("?isJoined", MySqlDbType.Bit, ParameterDirection.Output);
                        cmd.ExecuteNonQuery();
                        int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                        if(errorcode == -1)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            result.errorMsg = "Token 验证失败";
                        }
                        else if(errorcode == 0)
                        {
                            bool isJoined = cmd.Parameters["isJoined"].Value.toBoolean().Value;
                            result.dbReturningState = isJoined;
                        }
                    },
                    e =>
                    {
                        if(e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = e;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                        }
                    }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> GetGroupMembers(ISMGetGroupMembersRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                {
                    cmd.CommandText = "proc_client_get_group_members";
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                },
                e =>
                {
                    if (e != null)
                    {
                        if(e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = e;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                        }
                    }
                },
                data =>
                {
                    if(data.Count == 1 && data.First().ContainsKey("error"))
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    else if (data.Count == 1 && data.First().ContainsKey("bad_user"))
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_AUTHORIZERIGHTSFAIL;
                        result.errorMsg = "用户不属于该群组，无权查看群成员";
                    }
                    else if (data.Count == 1 && data.First().ContainsKey("group_dismissed"))
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                        result.errorMsg = "该群已解散";
                    }
                    else
                    {
                        List<ISMGroupMember> members = new List<ISMGroupMember>();
                        data.ForEach(d =>
                        {
                            ISMGroupMember member = new ISMGroupMember()
                            {
                                info = new ISMUserinfo()
                                {
                                    ID = d["uid"].ToString().toInt64().Value,
                                    openId = d["openid"].ToString(),
                                    intopenid = d["intopenid"].ToString(),
                                    wechatName = d["wechatname"].ToString(),
                                    username = d["username"].ToString(),
                                    sex = (Sex)d["sex"].ToString().toInt32().Value,
                                    vocation = d["vocation"].ToString(),
                                    company = d["company"].ToString(),
                                    occupation = d["occupation"].ToString(),
                                    mobile = d["mobile"].ToString(),
                                    telephone = d["telephone"].ToString(),
                                    email = d["email"].ToString(),
                                    officeAddress = d["officeaddress"].ToString(),
                                    piccardUrl = d["piccardUrl"].ToString(),
                                    videocardUrl = d["piccardUrl"].ToString(),
                                    headimgUrl = d["headimgUrl"].ToString()
                                },
                                role = d["group_policy_role"].ToString()
                            };
                            members.Add(member);
                        });
                        result.dbReturningState = members;
                    }
                },CommandType.StoredProcedure,false);
                return result;
            });
        }
        private Task<ISMServiceResult> GetGroupMessages(ISMGetGroupMessageRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                {
                    cmd.CommandText = "proc_client_get_group_messages";
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?startIdx", request.page * request.pageSize, ParameterDirection.Input);
                    cmd.Parameters.Add("?endIdx", (request.page + 1) * request.pageSize, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                },
                e =>
                {
                    if(e != null)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                        result.errorMsg = e;
                    }
                },
                data =>
                {
                    if(data.Count == 1 && data.First().ContainsKey("error"))
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    if (data.Count == 1 && data.First().ContainsKey("group_dismissed"))
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                        result.errorMsg = "该群已解散";
                    }
                    else
                    {
                        List<ISMGroupMessage> messages = new List<ISMGroupMessage>();
                        data.ForEach(d =>
                        {
                            ISMGroupMessage message = new ISMGroupMessage()
                            {
                                ID = d["ID"].toUInt64().Value,
                                group_message = d["group_message"].ToString(),
                                type = d["message_type"].toEnum<GroupMessageType>(),
                                timetag = d["timetag"].ToString(),
                                publisher = new ISMUserinfo(){
                                    ID = d["uid"].ToString().toInt64().Value,
                                    openId = d["openid"].ToString(),
                                    intopenid = d["intopenid"].ToString(),
                                    wechatName = d["wechatname"].ToString(),
                                    username = d["username"].ToString(),
                                    sex = (Sex)d["sex"].ToString().toInt32().Value,
                                    vocation = d["vocation"].ToString(),
                                    company = d["company"].ToString(),
                                    occupation = d["occupation"].ToString(),
                                    mobile = d["mobile"].ToString(),
                                    telephone = d["telephone"].ToString(),
                                    email = d["email"].ToString(),
                                    officeAddress = d["officeaddress"].ToString(),
                                    piccardUrl = d["piccardUrl"].ToString(),
                                    videocardUrl = d["piccardUrl"].ToString(),
                                    headimgUrl = d["headimgUrl"].ToString()
                                },
                                images = new List<UploadImageEntity>()
                            };
                            string imgs = d["img_urls"].ToString();
                            if (imgs != "#na")
                            {
                                int i = 0;
                                imgs.Split('&').ToList().ForEach(img =>
                                {
                                    try
                                    {
                                        Model.Images.UploadImageEntity entity = new Model.Images.UploadImageEntity()
                                        {
                                            imageID = d["img_ids"].ToString().Split('&')[i].toInt64().Value,
                                            ori_image_url = img
                                        };
                                        entity.generateThumbs();
                                        message.images.Add(entity);
                                    }
                                    catch (Exception e) { }
                                    i++;
                                });
                            }
                            if(message.type == GroupMessageType.kGroupMessageTypeShared)
                            {
                                ISMShare share = new ISMShare()
                                {
                                    share_desc = d["share_desc"].ToString(),
                                    share_title = d["share_title"].ToString(),
                                    share_image_url = d["share_image"].ToString(),
                                    share_link = d["share_link"].ToString()
                                };
                                message.group_share = share;
                            }
                            messages.Add(message);
                        });
                        result.dbReturningState = messages;
                    }
                }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> DismissGroup(ISMDismissGroupRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                {
                    cmd.CommandText = "proc_client_dismiss_group";
                    cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                    cmd.ExecuteNonQuery();
                    int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                    if(errorcode == -1)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    else if(errorcode == -2)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_AUTHORIZERIGHTSFAIL;
                        result.errorMsg = "权限不足";
                    }
                },
                e =>
                {
                    if(e != null)
                    {
                        result.isOperationSuccess = false;
                        result.errorMsg = e;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                    }
                }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> RemoveMemberFromGroup(ISMRemoveUserFromGroupRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                {
                    cmd.CommandText = "proc_client_exit_group";
                    cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                    cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                    cmd.Parameters.Add("?_operator", request.group_operator, ParameterDirection.Input);
                    cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                    cmd.ExecuteNonQuery();
                    int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                    if (errorcode == -1)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        result.errorMsg = "Token 验证失败";
                    }
                    else if (errorcode == -2)
                    {
                        result.isOperationSuccess = false;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_AUTHORIZERIGHTSFAIL;
                        result.errorMsg = "权限不足";
                    }
                },
                e =>
                {
                    if (e != null)
                    {
                        result.isOperationSuccess = false;
                        result.errorMsg = e;
                        result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                    }
                }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> GetGroupJoins(ISMGetGroupJoinRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                    {
                        cmd.CommandText = "proc_client_get_group_join_requests";
                        cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                        cmd.Parameters.Add("?_groupid", request.group_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    },
                    e =>
                    {
                        if(e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = e;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                        }
                    },
                    data =>
                    {
                        if (data.Count == 1 && data.First().ContainsKey("error"))
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            result.errorMsg = "Token 验证失败";
                        }
                        else if (data.Count == 1 && data.First().ContainsKey("group_dismissed"))
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                            result.errorMsg = "该群已解散";
                        }
                        else if(data.Count == 1 && data.First().ContainsKey("no_rights"))
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_AUTHORIZERIGHTSFAIL;
                            result.errorMsg = "权限不足";
                        }
                        else
                        {
                            List<ISMGroupJoinRequest> requests = new List<ISMGroupJoinRequest>();
                            data.ForEach(d =>
                            {
                                ISMGroupJoinRequest req = new ISMGroupJoinRequest()
                                {
                                    ID = d["ID"].toUInt64().Value,
                                    content = d["content"].ToString(),
                                    status = d["status"].toEnum<GroupRequestStatus>(),
                                    timetag = d["timetag"].ToString(),
                                    info = new ISMUserinfo()
                                    {
                                        ID = d["uid"].ToString().toInt64().Value,
                                        openId = d["openid"].ToString(),
                                        intopenid = d["intopenid"].ToString(),
                                        wechatName = d["wechatname"].ToString(),
                                        username = d["username"].ToString(),
                                        sex = (Sex)d["sex"].ToString().toInt32().Value,
                                        vocation = d["vocation"].ToString(),
                                        company = d["company"].ToString(),
                                        occupation = d["occupation"].ToString(),
                                        mobile = d["mobile"].ToString(),
                                        telephone = d["telephone"].ToString(),
                                        email = d["email"].ToString(),
                                        officeAddress = d["officeaddress"].ToString(),
                                        piccardUrl = d["piccardUrl"].ToString(),
                                        videocardUrl = d["piccardUrl"].ToString(),
                                        headimgUrl = d["headimgUrl"].ToString()
                                    }
                                };
                                requests.Add(req);
                            });
                            result.dbReturningState = requests;
                        }
                    },CommandType.StoredProcedure,false);
                return result;
            });
        }
        private Task<ISMServiceResult> GetGroupMessageComments(ISMGetGroupMessageCommentsRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                    {
                        cmd.CommandText = "proc_client_get_group_message_comments";
                        cmd.Parameters.Add("?_group_message_id", request.group_message_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?startIdx", request.page * request.pageSize, ParameterDirection.Input);
                        cmd.Parameters.Add("?endIdx", (request.page + 1) * request.pageSize, ParameterDirection.Input);
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    },
                    e =>
                    {
                        if(e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            result.errorMsg = e;
                        }
                    },
                    data =>
                    {
                        if(data.Count == 1 && data.First().ContainsKey("error"))
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = "Token 验证失败";
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        }
                        else
                        {
                            List<ISMGroupMessageComment> comments = new List<ISMGroupMessageComment>();
                            data.ForEach(d =>
                            {
                                ISMGroupMessageComment comment = new ISMGroupMessageComment()
                                {
                                    timetag = d["timetag"].ToString(),
                                    comment = d["comment"].ToString(),
                                    info = new ISMUserinfo()
                                    {
                                        ID = d["uid"].ToString().toInt64().Value,
                                        openId = d["openid"].ToString(),
                                        intopenid = d["intopenid"].ToString(),
                                        wechatName = d["wechatname"].ToString(),
                                        username = d["username"].ToString(),
                                        sex = (Sex)d["sex"].ToString().toInt32().Value,
                                        vocation = d["vocation"].ToString(),
                                        company = d["company"].ToString(),
                                        occupation = d["occupation"].ToString(),
                                        mobile = d["mobile"].ToString(),
                                        telephone = d["telephone"].ToString(),
                                        email = d["email"].ToString(),
                                        officeAddress = d["officeaddress"].ToString(),
                                        piccardUrl = d["piccardUrl"].ToString(),
                                        videocardUrl = d["piccardUrl"].ToString(),
                                        headimgUrl = d["headimgUrl"].ToString()
                                    }
                                };
                                comments.Add(comment);
                            });
                            result.dbReturningState = comments;
                        }
                    }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> AddGroupMessageComment(ISMAddGroupMessageCommentRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperation(cmd =>
                    {
                        cmd.CommandText = "proc_client_add_group_message_comment";
                        cmd.Parameters.Add("?_group_message_id", request.group_message_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?_comment", request.comment, ParameterDirection.Input);
                        cmd.Parameters.Add("?_commenter", request.commenter, ParameterDirection.Input);
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                        cmd.ExecuteNonQuery();
                        int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                        if(errorcode == -1)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = "Token 验证失败";
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                        }
                    },
                    e =>
                    {
                        if(e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            result.errorMsg = e;
                        }
                    }, CommandType.StoredProcedure, false);
                return result;
            });
        }
        private Task<ISMServiceResult> GetSingleGroupMessage(ISMGetSingleGroupMessageRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                    {
                        cmd.CommandText = "proc_client_get_single_group_message";
                        cmd.Parameters.Add("?_group_message_id", request.group_message_id, ParameterDirection.Input);
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                    },
                    e =>
                    {
                        if (e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            result.errorMsg = e;
                        }
                    },
                    data =>
                    {
                        if (data.Count == 1 && data.First().ContainsKey("error"))
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            result.errorMsg = "Token 验证失败";
                        }
                        else if (data.Count == 1 && data.First().ContainsKey("group_dismissed"))
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_GROUP_GROUP_NOT_EXISTS;
                            result.errorMsg = "群组不存在或消息非法";
                        }
                        else if(data.Count == 0)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                            result.errorMsg = "无此消息";
                        }
                        else
                        {
                            var d = data.First();
                            ISMGroupMessage message = new ISMGroupMessage()
                            {
                                ID = d["ID"].toUInt64().Value,
                                group_message = d["group_message"].ToString(),
                                type = d["message_type"].toEnum<GroupMessageType>(),
                                timetag = d["timetag"].ToString(),
                                publisher = new ISMUserinfo()
                                {
                                    ID = d["uid"].ToString().toInt64().Value,
                                    openId = d["openid"].ToString(),
                                    intopenid = d["intopenid"].ToString(),
                                    wechatName = d["wechatname"].ToString(),
                                    username = d["username"].ToString(),
                                    sex = (Sex)d["sex"].ToString().toInt32().Value,
                                    vocation = d["vocation"].ToString(),
                                    company = d["company"].ToString(),
                                    occupation = d["occupation"].ToString(),
                                    mobile = d["mobile"].ToString(),
                                    telephone = d["telephone"].ToString(),
                                    email = d["email"].ToString(),
                                    officeAddress = d["officeaddress"].ToString(),
                                    piccardUrl = d["piccardUrl"].ToString(),
                                    videocardUrl = d["piccardUrl"].ToString(),
                                    headimgUrl = d["headimgUrl"].ToString()
                                },
                                images = new List<UploadImageEntity>()
                            };
                            string imgs = d["img_urls"].ToString();
                            if (imgs != "#na")
                            {
                                int i = 0;
                                imgs.Split('&').ToList().ForEach(img =>
                                {
                                    try
                                    {
                                        Model.Images.UploadImageEntity entity = new Model.Images.UploadImageEntity()
                                        {
                                            imageID = d["img_ids"].ToString().Split('&')[i].toInt64().Value,
                                            ori_image_url = img
                                        };
                                        entity.generateThumbs();
                                        message.images.Add(entity);
                                    }
                                    catch (Exception e) { }
                                    i++;
                                });
                            }
                            if (message.type == GroupMessageType.kGroupMessageTypeShared)
                            {
                                ISMShare share = new ISMShare()
                                {
                                    share_desc = d["share_desc"].ToString(),
                                    share_title = d["share_title"].ToString(),
                                    share_image_url = d["share_image"].ToString(),
                                    share_link = d["share_link"].ToString()
                                };
                                message.group_share = share;
                            }
                            result.dbReturningState = message;
                        }
                    }, CommandType.StoredProcedure, false);
                return result;
            });
        }
    }
}
